package com.example.demo12;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {
    private SharedPreferences sharedPreferences = null;
    private SharedPreferences.Editor edit = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final Button saveFile=findViewById(R.id.saveFile);
        final Button readFile=findViewById(R.id.readFile);
        final EditText inputData=findViewById(R.id.text_input);
        final TextView outputData=findViewById(R.id.text_output);
        saveFile.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String data = inputData.getText().toString();
                boolean flag = saveFile(data);
                if (flag){
                    Toast.makeText(getApplicationContext(),"数据添加成功",Toast.LENGTH_SHORT).show();
                }else {
                    Toast.makeText(getApplicationContext(),"数据添加失败",Toast.LENGTH_SHORT).show();

                }
            }
        });
        readFile.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String data = readFile();
                outputData.setText(data);
            }
        });
    }

    private String readFile() {
        String data = sharedPreferences.getString("1", "无数据");
        return data;
    }

    private boolean saveFile(String data) {
        sharedPreferences = getSharedPreferences("data", Context.MODE_PRIVATE);
        edit = sharedPreferences.edit();
        PreferenceManager.getDefaultSharedPreferences(this);
        edit.putString("1",data);
        edit.apply();
        return true;
    }
}
